<template>
  <div class="gap-col-8 px-4 pt-2">
    <div class="font-size-14 font-weight-500 line-height-125">
      <i18n-t keypath="search.result.photos" tag="div" class="font-size-14 font-weight-500 line-height-125">
        <template #keyword>
          <span class="text-primary">{{ searchText }}</span>
        </template>
        <template #num>
          <span>{{ fetcher.photo.dataExtra?.total }}</span>
        </template>
      </i18n-t>
    </div>
    <MediaRow
      :items="fetcher.photo.dataList"
      :loading="fetcher.photo.loading"
      :no-more="fetcher.photo.noMore"
      no-padding
      @intersect="fetcher.photo.nextPage"
      @click:item="onItemClick"
    ></MediaRow>
  </div>
</template>
<script setup>
import { onActivated, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useSearchResultStore, useSearchStore } from '@/store/search'
import MediaRow from '@/components/media/MediaRow.vue'
import { useInfinite } from '@/compositions/request/infinite'
import { MEDIA_TYPE } from '@/constant'
import { trackEvent } from '@/gtm'
import API from '@/http'

const searchStore = useSearchStore()
const { media } = storeToRefs(searchStore)
const { toIndexedMainViewer, toMainViewer } = searchStore
const { searchText, hasSearchText } = storeToRefs(useSearchResultStore())

const fetcher = ref({
  photo: useInfinite({
    request: API.Search.image,
    params: hasSearchText.value ? { keyword: searchText.value } : {},
    limit: import.meta.env.VITE_MEDIA_LIST_LIMIT ?? 12,
  }),
})
onActivated(() => {
  media.value = MEDIA_TYPE.PHOTO
  toMainViewer(fetcher.value)
  trackEvent({ key: 32, value: null, meta: { keyword: searchText.value } })
})

watch(searchText, (keyword) => {
  if (!hasSearchText.value) {
    return
  }
  fetcher.value.photo.refresh({ newParams: { keyword } })
  trackEvent({ key: 32, value: null, meta: { keyword } })
})

function onItemClick(index) {
  toIndexedMainViewer(index)
}
</script>
